package com.xhwl.logistics.util;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * 防止模糊查询中的sql注入
 */
public class EscapeCharacter {

    public static final EscapeCharacter DEFAULT;
    private static final List<String> TO_REPLACE;
    private static char escapeCharacter;

    //将value中的”%“和”_“前加上"\"
    public static String escape(String value) {
        return (value == null) ? null
                : Stream.concat(Stream.of(String.valueOf(escapeCharacter)), EscapeCharacter.TO_REPLACE.stream())
                .reduce(value, (it, character) -> it.replace(character, escapeCharacter + character));
    }

    private EscapeCharacter(char escapeCharacter1) {
        escapeCharacter = escapeCharacter1;
    }

    public static EscapeCharacter of(char escapeCharacter) {
        return new EscapeCharacter(escapeCharacter);
    }

    public char getEscapeCharacter() {
        return escapeCharacter;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof EscapeCharacter)) {
            return false;
        }
        EscapeCharacter other = (EscapeCharacter) o;
        return this.getEscapeCharacter() == other.getEscapeCharacter();
    }

    @Override
    public int hashCode() {
        int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getEscapeCharacter();
        return result;
    }

    @Override
    public String toString() {
        return "EscapeCharacter(escapeCharacter=" + this.getEscapeCharacter() + ")";
    }

    static {
        DEFAULT = of('\\');
        TO_REPLACE = Arrays.asList("_", "%");
    }
}
